package club.blueline.consumer.controller;

import club.blueline.consumer.entity.EditCommentDto;
import club.blueline.consumer.entity.PostCommentDto;
import club.blueline.consumer.entity.Result;
import club.blueline.consumer.entity.ResultCode;
import club.blueline.consumer.mapper.SimpleMapper;
import club.blueline.consumer.service.CommentService;
import club.blueline.consumer.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Resource
    private SimpleMapper simpleMapper;

    @PostMapping
    public Result postComment(@RequestBody PostCommentDto postCommentVo) {
        return commentService.postComment(postCommentVo);
    }

    @PutMapping
    public Result editComment(@RequestBody EditCommentDto editCommentVo, HttpServletRequest request) {
        String idStr = request.getHeader("Authorization-id");
        String role = request.getHeader("Authorization-role");
        if(role.equals("ROLE_ADMIN") || idStr.equals(String.valueOf(simpleMapper.getUserIdByCommentId(editCommentVo.getId()))))
            return commentService.editComment(editCommentVo);
        else {
            Result res = ResultUtils.genFailResult("未授权行为！");
            res.setCode(ResultCode.UNAUTHORIZED.code());
            return res;
        }
    }

    @DeleteMapping
    public Result deleteComment(@RequestParam(value = "id",required = false) Integer id, HttpServletRequest request) {
        if(id == null) {
            Result res = ResultUtils.genFailResult("缺少参数id");
            res.setCode(ResultCode.FAIL.code());
            return res;
        }
        String idStr = request.getHeader("Authorization-id");
        String role = request.getHeader("Authorization-role");
        if(role.equals("ROLE_ADMIN") || idStr.equals(String.valueOf(simpleMapper.getUserIdByCommentId(id))))
            return commentService.deleteComment(id);
        else {
            Result res = ResultUtils.genFailResult("未授权行为！");
            res.setCode(ResultCode.UNAUTHORIZED.code());
            return res;
        }
    }

}
